package com.ztsoft.user.service.dynamic.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ztsoft.user.mapper.dynamic.ColumnDescriptionMapper;
import com.ztsoft.user.mapper.dynamic.MetaTableMapper;
import com.ztsoft.user.pojo.entity.dynamic.ColumnDescription;
import com.ztsoft.user.service.dynamic.MetaTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service(value = "metaTableService")
public class MetaTableServiceImpl implements MetaTableService {
    @Autowired
    private MetaTableMapper metaTableMapper;
    @Autowired
    private ColumnDescriptionMapper columnDescriptionMapper;

    @Override
    public List<String> listTables() {
        return metaTableMapper.listTables();
    }

    @Override
    public List<Map> listTableColumn(String tableName, String tableCode, String deptId) {
        String[] split = tableName.split("#");
        List<Map> list = new ArrayList<>();
        for (String name : split) {
            List<Map> tableColumn = metaTableMapper.listTableColumn(name);
            for (Map map : tableColumn) {
                String field = (String) map.get("COLUMN_NAME");
                QueryWrapper<ColumnDescription> wrapper = new QueryWrapper<>();
                wrapper.eq("select_field", field.replace("#", "."))
                        .eq("table_code", tableCode)
                        .eq("dept_id", deptId);
                int count = columnDescriptionMapper.selectCount(wrapper);
                if (count == 0) {
                    map.put("disabled ", false);
                } else {
                    map.put("disabled", true);
                }
            }
            list.addAll(tableColumn);
        }

        return list;
    }
}